<template>
  <el-card class="box-card">
    <div style="line-height: 0px">
      <el-form :inline="true" class="demo-form-inline" size="small">
        <el-form-item>
          <el-input
            v-model="formInline.username"
            clearable
            placeholder="角色姓名"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button @click="queryUserList">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="dialogFormVisible = true"
            >新增</el-button
          >
        </el-form-item>
        <el-form-item>
          <el-button
            type="danger"
            @click="deleteList()"
            :disabled="multipleSelection.length === 0"
            >删除</el-button
          >
        </el-form-item>
      </el-form>
      <el-table
        stripe
        :data="userList"
        style="width: 100%"
        @selection-change="handleSelectionChange"
        :cell-style="{ 'text-align': 'center' }"
        :header-cell-style="{ 'text-align': 'center' }"
        highlight-current-row
      >
        <el-table-column class="table-selection" type="selection" width="55">
        </el-table-column>
        <el-table-column prop="userId" label="id" width="60"> </el-table-column>
        <el-table-column prop="username" label="姓名" width="90">
        </el-table-column>
        <el-table-column prop="email" label="邮箱" width="200">
        </el-table-column>
        <el-table-column prop="mobile" label="电话" width="190">
        </el-table-column>
        <el-table-column label="状态" width="80">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.status"
              :active-value="1"
              :inactive-value="0"
              active-color="#13ce66"
              inactive-color="#ff4949"
              @change="changeSwitch(scope.row)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="210">
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="primary"
              @click="handleEdit(scope.$index, scope.row)"
              >编辑</el-button
            >
            <el-button
              size="mini"
              type="danger"
              @click="handleDelete(scope.$index, scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <div class="block">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="this.pageIndex"
          :page-sizes="[5, 10, 15, 20]"
          :page-size="this.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="this.total"
        >
        </el-pagination>
      </div>
      <!-- dialog窗口(新增) -->
      <el-dialog title="新增" :visible.sync="dialogFormVisible" width="45%">
        <el-form
          ref="addForm"
          :model="addForm"
          :rules="addFormRules"
          label-width="80px"
        >
          <el-row>
            <el-col :span="12">
              <el-form-item label="用户名称" prop="username">
                <el-input
                  v-model="addForm.username"
                  placeholder="请输入用户名称"
                  maxlength="15"
                /> </el-form-item
            ></el-col>
            <el-col :span="12">
              <el-form-item label="角色" prop="role">
                <el-select v-model="addForm.role" placeholder="角色">
                  <el-option
                    v-for="item in options"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  >
                  </el-option>
                </el-select> </el-form-item
            ></el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="密码" prop="password">
                <el-input
                  v-model="addForm.password"
                  placeholder="请输入用户密码"
                  type="password"
                  maxlength="20"
                /> </el-form-item
            ></el-col>
          </el-row>
          <el-row>
            <el-col :span="24"
              ><el-form-item label="电话">
                <el-input
                  v-model="addForm.mobile"
                  placeholder="请输入用户电话"
                  maxlength="20"
                /> </el-form-item
            ></el-col>
          </el-row>
          <el-row>
            <el-col :span="24"
              ><el-form-item label="邮箱">
                <el-input
                  v-model="addForm.email"
                  placeholder="请输入邮箱"
                  maxlength="50"
                /> </el-form-item
            ></el-col>
          </el-row>
          <el-row>
            <el-col :span="24"
              ><el-form-item label="备注">
                <el-input
                  v-model="addForm.remark"
                  placeholder="备注"
                  type="textarea"
                  maxlength="200"
                /> </el-form-item
            ></el-col>
          </el-row>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button
            type="primary"
            @click="submitForm(addForm)"
            :loading="addLoading"
            >确 定</el-button
          >
        </div>
      </el-dialog>

      <!-- dialog窗口(编辑) -->
      <el-dialog
        title="编辑用户信息"
        :visible.sync="dialogFormVisibleEdit"
        width="45%"
      >
        <el-form
          ref="rowData"
          :model="rowData"
          :rules="editFormRules"
          label-width="80px"
        >
          <el-row>
            <el-col :span="12">
              <el-form-item label="用户名称" prop="username">
                <el-input
                  v-model="rowData.username"
                  placeholder="请输入用户名称"
                  maxlength="15"
                /> </el-form-item
            ></el-col>
            <el-col :span="12">
              <el-form-item label="状态:" prop="status">
                <el-radio v-model="rowData.status" label="1">正常</el-radio>
                <el-radio v-model="rowData.status" label="0">停用</el-radio>
              </el-form-item></el-col
            >
          </el-row>
          <el-row>
            <el-col :span="24"
              ><el-form-item label="电话" prop="mobile">
                <el-input
                  v-model="rowData.mobile"
                  placeholder="请输入用户电话"
                  maxlength="20"
                /> </el-form-item
            ></el-col>
          </el-row>
          <el-row>
            <el-col :span="24"
              ><el-form-item label="邮箱" prop="email">
                <el-input
                  v-model="rowData.email"
                  placeholder="请输入邮箱"
                  maxlength="50"
                /> </el-form-item
            ></el-col>
          </el-row>
          <el-row>
            <el-col :span="24"
              ><el-form-item label="备注" prop="remark">
                <el-input
                  v-model="rowData.remark"
                  placeholder="备注"
                  type="textarea"
                  maxlength="200"
                /> </el-form-item
            ></el-col>
          </el-row>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisibleEdit = false">取 消</el-button>
          <el-button
            type="primary"
            @click="submitUpdate()"
            :loading="updateLoading"
            >确 定</el-button
          >
        </div>
      </el-dialog>
    </div>
  </el-card>
</template>

<script>
export default {
  name: "SysUser",
  data() {
    var validateCheckExist = (rule, value, callback) => {
      switch (rule.field) {
        case "username":
          if (this.proData.username == "" || this.proData.username !== value) {
            this.$http
              .get("/sys/sysUser/checkExist?key=" + rule.field + "&value=" + value)
              .then((res) => {
                if (res.data.data > 0) {
                  callback(new Error("用户名称已存在"));
                } else {
                  callback();
                }
              });
          } else {
            callback();
          }

          break;
        case "email":
          if (this.proData.email == "" || this.proData.email !== value) {
            this.$http
              .get(
                "/sys/sysUser/checkExist?key=" + rule.field + "&value=" + value
              )
              .then((res) => {
                if (res.data.data > 0) {
                  callback(new Error("邮箱已存在"));
                } else {
                  callback();
                }
              });
          } else {
            callback();
          }

          break;
        case "mobile":
          if (this.proData.mobile == "" || this.proData.mobile !== value) {
            this.$http
              .get(
                "/sys/sysUser/checkExist?key=" + rule.field + "&value=" + value
              )
              .then((res) => {
                if (res.data.data > 0) {
                  callback(new Error("手机号已存在"));
                } else {
                  callback();
                }
              });
          } else {
            callback();
          }

          break;
      }
    };
    return {
      options: [
        {
          value: "选项1",
          label: "管理员",
        },
        {
          value: "选项2",
          label: "普通角色",
        },
      ],
      addFormRules: {
        username: [
          { required: true, message: "请输入用户名称", trigger: "blur" },
          { validator: validateCheckExist, trigger: "blur" },
        ],
        password: [{ required: true, message: "请输入密码", trigger: "blur" }],
        role: [{ required: true, message: "请输入角色名称", trigger: "blur" }],
      },
      editFormRules: {
        username: [
          { required: true, message: "请输入用户名称", trigger: "blur" },
          { validator: validateCheckExist, trigger: "blur" },
        ],
        email: [{ validator: validateCheckExist, trigger: "blur" }],
        mobile: [{ validator: validateCheckExist, trigger: "blur" }],
      },
      rowData: {
        userId: "",
        password: "",
        username: "",
        remark: "",
        email: "",
        mobile: "",
        status: "",
      },
      proData: {
        username: "",
        email: "",
        mobile: "",
      },
      multipleSelection: [],
      addForm: {
        username: "",
        password: "",
        email: "",
        mobile: "",
        password: "",
        role: "",
        remark: "",
      },
      formInline: {
        username: "",
      },
      userList: [],
      pageIndex: 1,
      pageSize: 10,
      total: 0,
      dataListLoading: false,
      dialogFormVisible: false,
      dialogFormVisibleEdit: false,
      addLoading: false,
      updateLoading: false,
    };
  },
  methods: {
    changeSwitch(row) {
      let text = row.status == 0 ? "停用" : "启用";
      this.$confirm("确定要" + text + row.username + "用户吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$http
            .get(
              "/sys/sysUser/updateStatus?userId=" +
                row.userId +
                "&status=" +
                row.status
            )
            .then((res) => {
              if (res.data.data == true) {
                this.$message({
                  type: "success",
                  message: text + "成功",
                });
              } else {
                this.$message({
                  type: "warning",
                  message: "系统繁忙!",
                });
              }
            });
        })
        .catch(() => {
          row.status = row.status == 1 ? 0 : 1;
        });
    },
    deleteList() {
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$http
            .post("/sys/sysUser/deleteList", this.multipleSelection)
            .then((res) => {
              if (res.data.data > 0) {
                this.$message({
                  type: "success",
                  message: "删除成功!共删除" + res.data.data + "条记录",
                });
                this.queryUserList();
              } else {
                this.$message({
                  type: "warning",
                  message: "系统繁忙!",
                });
              }
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    handleSelectionChange(val) {
      this.multipleSelection = [];
      val.forEach((element) => {
        this.multipleSelection.push(element.userId);
      });
    },
    handleEdit(index, row) {
      this.proData.username = this.rowData.username = row.username;
      this.rowData.userId = row.userId;
      this.rowData.remark = row.remark;
      this.proData.email = this.rowData.email = row.email;
      this.proData.mobile = this.rowData.mobile = row.mobile;
      this.rowData.status = row.status == 1 ? "1" : "0";
      this.dialogFormVisibleEdit = true;
      this.$nextTick(() => {
        this.$refs["rowData"].clearValidate(); // 只清除清除验证
      });
    },
    handleDelete(index, row) {
      this.$confirm(
        "是否确认永久删除id为" + row.userId + "的用户?该操作是不可逆的",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(() => {
          this.$http
            .get("/sys/sysUser/deleteOne?userId=" + row.userId)
            .then((res) => {
              if (res.data.data) {
                this.$message({
                  type: "success",
                  message: "删除成功!",
                });
                this.queryUserList();
              } else {
                this.$message({
                  type: "warning",
                  message: "系统繁忙!",
                });
              }
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    submitForm(addForm) {
      this.$refs["addForm"].validate((valid) => {
        if (valid) {
          if (this.addLoading == true) return;
          this.addLoading = true;
          this.$http.post("/sys/sysUser/save", addForm).then((res) => {
            if (res.data.data) {
              this.$message({
                message: "添加用户成功",
                type: "success",
              });

              this.addLoading = false;
              this.addForm = {};
              this.dialogFormVisible = false;

              this.queryUserList();
            } else {
              this.$message.error({
                message: "系统繁忙",
              });
            }
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    submitUpdate() {
      this.$refs["rowData"].validate((valid) => {
        if (valid) {
          this.updateLoading = true;
          this.$http
            .post("/sys/sysUser/updateOne", this.rowData)
            .then((res) => {
              if (res.data.data) {
                this.$message({
                  message: "修改成功",
                  type: "success",
                });
                this.dialogFormVisibleEdit = false;
                this.updateLoading = false;
                this.queryUserList();
              } else {
                this.$message.error({
                  message: "系统繁忙",
                });
              }
            });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.pageIndex = 1;
      this.queryUserList();
    },
    handleCurrentChange(val) {
      this.pageIndex = val;
      this.queryUserList();
    },
    queryUserList() {
      if (this.dataListLoading) return;
      this.dataListLoading = true;
      const params = {
        params: {
          pageIndex: this.pageIndex,
          pageSize: this.pageSize,
          username: this.formInline.username,
        },
      };
      this.$http.get("/sys/sysUser/queryList", params).then((res) => {
        this.userList = res.data.data.list;
        this.total = res.data.data.totalCount;
        this.dataListLoading = false;
      });
    },
  },
  computed: {},
  mounted() {
    this.queryUserList();
  },
};
</script>

<style>
</style>